package com.chinda.common.page;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinda.common.xss.SQLFilter;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author Wang Chinda
 * @date 2020/8/8
 * @see
 * @since 1.0
 */
@Getter
@Setter
public abstract class BaseQO<T> implements Serializable {
    private static final long serialVersionUID = -45200812016536165L;
    /**
     * 每页显示多少条
     */
    private Integer pageSize = 20;
    /**
     * 当前页码
     */
    private Integer currPage = 1;
    /**
     * 排序
     */
    private String order;
    /**
     * 排序字段
     */
    private String orderField;

    public IPage<T> getPage() {
        //分页对象
        Page<T> page = new Page<>(this.currPage, this.pageSize);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderColumn = SQLFilter.sqlInject(this.orderField);

        //前端字段排序
        if (StrUtil.isNotEmpty(orderColumn)) {
            if (SqlKeyword.DESC.name().equalsIgnoreCase(this.order)) {
                return page.addOrder(OrderItem.desc(orderColumn));
            }
            return page.addOrder(OrderItem.asc(orderColumn));
        }
        return page;
    }

    /**
     * 获取动态sql
     *
     * @return
     */
    public abstract QueryWrapper<T> getQueryWrapper();
}
